import os
import logging
from datetime import datetime

import pandas as pd

import pyJianYingDraft as draft
from pyJianYingDraft import Font_type, Text_style, trange, Export_resolution, Export_framerate, \
    Extend_mode, Timerange

# 初始化日志
logging.basicConfig(level=logging.INFO, format="%(asctime)s - %(levelname)s - %(message)s")
logger = logging.getLogger(__name__)

# 常量定义
TEMPLATE_NAME = "美女与野兽"
COMBO_NAME = "美女与野兽-1"
INPUT_ROOT = r"D:\PycharmProjects\JesterWisdom\output\alluring"
excel_path = r"D:\PycharmProjects\JesterWisdom\assets\alluring\生图提示词.xlsx"
OUTPUT_PATH = "D:\\批量_视频保存\\美女与野兽"  # 请根据实际路径修改

DRAFT_PATH = os.path.join(
    # LOCALAPPDATA 是 Windows 系统中的一个环境变量，表示当前用户的本地应用程序数据存储路径
    # C:\Users\<用户名>\AppData\Local
    os.getenv("LOCALAPPDATA"),
    "JianyingPro\\User Data\\Projects\\com.lveditor.draft"
)


def import_subtitles(script, srt_path):
    """
    导入 SRT 字幕文件到视频轨道中。

    Args:
        script (draft.Script): 当前操作的脚本对象
        srt_path (str): SRT 字幕文件路径
    """
    logger.info("开始导入字幕...")
    try:
        text_segment = draft.Text_segment("文字", trange("0s", "10s"),
                                          font=Font_type.新青年体,
                                          border=draft.Text_border(width=30),
                                          style=Text_style(bold=True, italic=True, size=12,
                                                           color=(1.0, 1.0, 1.0),
                                                           underline=False,
                                                           align=1, alpha=1.0))
        text_segment.add_effect("7403996884856999194")  # 绿色
        text_segment.add_effect("7330165240576970021")  # 红色
        script.import_srt(srt_path, track_name="字幕2",
                          style_reference=text_segment,
                          clip_settings=draft.Clip_settings(transform_y=-0.5),
                          font_size=10)
        logger.info(f"成功导入SRT文件: {srt_path}")
    except Exception as e:
        logger.error(f"导入SRT失败: {e}")


def read_excel_data(excel_path):
    """
    读取 Excel 文件中的内容。

    :param excel_path: Excel 文件的路径
    :return: 包含 "英文翻译" 和 "中文句子" 的 DataFrame
    """
    df = pd.read_excel(excel_path)
    return df[["英文翻译", "中文句子"]]


def wrap_text_by_words(text, words_per_line=5):
    """
    按单词数量自动换行文本

    Args:
        text (str): 原始文本
        words_per_line (int): 每行单词数，默认为5

    Returns:
        str: 处理后的换行文本
    """
    if not isinstance(text, str):
        return str(text)

    words = text.split()
    lines = []

    # 按每5个单词分组
    for i in range(0, len(words), words_per_line):
        line_words = words[i:i + words_per_line]
        lines.append(' '.join(line_words))

    return '\n'.join(lines)

def wrap_text_by_words_cn(text, chars_per_line=5):
    """
    按字符数量自动换行文本（支持中英文）

    Args:
        text (str): 原始文本
        chars_per_line (int): 每行字符数，默认为5

    Returns:
        str: 处理后的换行文本
    """
    if not isinstance(text, str):
        return str(text)

    # 移除空格并将文本转换为字符列表
    chars = list(text.replace(' ', ''))
    lines = []

    # 按指定字符数分组
    for i in range(0, len(chars), chars_per_line):
        line_chars = chars[i:i + chars_per_line]
        lines.append(''.join(line_chars))

    return '\n'.join(lines)

def process_folder(folder_path, excel_path):
    """
    处理单个文件夹下的素材并生成视频

    Args:
        folder_path (str): 文件夹路径
    """
    try:
        logger.info(f"🔄 开始处理文件夹: {folder_path}")

        # df = read_excel_data(excel_path)
        folder_name = os.path.basename(folder_path)
        print(f"处理文件: {folder_name}")
        # row = int(folder_name.split('_')[1]) - 1
        # english_text = df.loc[row, "英文翻译"]
        # english_text = df.loc[row, "中文句子"]

        # 添加自动换行处理
        # wrapped_english_text = wrap_text_by_words_cn(english_text, 5)
        # wrapped_english_text = wrap_text_by_words(english_text, 5)

        # 构建素材路径
        image_files = [os.path.join(folder_path, f"{i}.jpg") for i in range(1, 6)]
        # 查找音频文件
        # wav_files = [f for f in os.listdir(folder_path) if f.lower().endswith(".wav")]
        # if not wav_files:
        #     logger.error(f"❌ 未找到 WAV 文件：{folder_path}")
        #     raise FileNotFoundError(f"未在文件夹 {folder_path} 中找到 .wav 音频文件")
        # audio_path = os.path.join(folder_path, wav_files[0])

        # srt_path = os.path.join(folder_path, "output.srt")
        logger.info("初始化剪映草稿模板...")
        draft_folder = draft.Draft_folder(DRAFT_PATH)
        # 初始化脚本
        script = draft_folder.duplicate_as_template(TEMPLATE_NAME, COMBO_NAME, allow_replace=True)
        # 替换标题
        # text_track = script.get_imported_track(draft.Track_type.text, index=0)
        # script.replace_text(text_track, 0, text=wrapped_english_text)
        # logger.info(f"替换【文本】title: {wrapped_english_text}")

        # 替换图片素材
        for i, img_path in enumerate(image_files, start=1):
            logger.info(f"🔄 替换图片素材 {i}.jpg")
            new_material = draft.Video_material(img_path)
            script, _ = script.replace_material_by_name(material_name=f"{i}.jpg", material=new_material)

        # 替换音频素材
        logger.info("🔄 增加音频素材")
        # audio_material = draft.Audio_material(audio_path)
        # script.replace_material_by_name(material_name="tts_audio_1.wav",
        #                                material=new_material)
        # script.add_track(draft.Track_type.audio, "语言", relative_index=1)
        #
        # audio_segment = draft.Audio_segment(audio_material, trange("0s", audio_material.duration / 0.7),
        #                                     speed=0.7, volume=0.9)

        # script.add_segment(audio_segment, '语言')
        # audio_track = script.get_imported_track(draft.Track_type.audio, index=0)
        # script.replace_material_by_seg(track=audio_track, segment_index=0,
        #                                material=new_material,
        #                                handle_extend=[draft.Extend_mode.extend_tail])

        # logger.info(f"替换【音频】素材: 口播音频.wav -> {audio_path}")

        # 导入字幕
        # if os.path.exists(srt_path):
        #     import_subtitles(script, srt_path)

        # 保存草稿
        script.save()
        logger.info("✅ 草稿保存完成")

        # 导出视频
        logger.info("🎬 开始导出视频")

        ctrl = draft.Jianying_controller()
        timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")  # 格式：年月日_时分秒
        output_path = os.path.join(OUTPUT_PATH, f"{COMBO_NAME}_{timestamp}.mp4")

        ctrl.export_draft(COMBO_NAME, output_path,
                          resolution=Export_resolution.RES_1080P,
                          framerate=Export_framerate.FR_24,
                          zi_mu=False,
                          kou_tu=False)
        logger.info(f"导出视频完成: {output_path}")

    except Exception as e:
        logger.error(f"❌ 处理文件夹失败: {e}")


def main():
    """
    主函数：遍历输入目录下的所有子文件夹并处理
    """
    logger.info("🚀 开始批量处理文件夹")
    print(os.listdir(INPUT_ROOT))
    for folder_name in os.listdir(INPUT_ROOT):
        folder_path = os.path.join(INPUT_ROOT, folder_name)
        if os.path.isdir(folder_path):
            process_folder(folder_path, excel_path)
    logger.info("🎉 所有文件夹处理完成")


if __name__ == "__main__":
    main()
